(function() {
	var bookmarklet = {
		/***************************************************************************
		 * Common libs 
		 ****************************************************************************/
		bindEvent : function(elem, evnt, func) {
			if (elem.addEventListener)
				elem.addEventListener(evnt, func, false);
			else if (elem.attachEvent)// For IE
				return elem.attachEvent("on" + evnt, func);
		}, 
		
		getHeight: function() {
			var body = document.body, html = document.documentElement;
			var height = Math.max(
				body.scrollHeight, 
				body.offsetHeight, 
				html.clientHeight, 
				html.scrollHeight, 
				html.offsetHeight);
			return height;
		},		
		
		hasClass: function (ele, cls) {
			return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
		}, 
		
		addClass: function (ele, cls) {
			if (!this.hasClass(ele, cls))
				ele.className += " " + cls;
		}, 
		
		removeClass: function(ele, cls) {
			if (this.hasClass(ele, cls)) {
				var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
				ele.className = ele.className.replace(reg, ' ');
			}
		}, 
		
		/***************************************************************************
		 * Bookmarklet functions
		 ***************************************************************************/
				
		// Properties
		width : [200, 1000, 300], //min, max, display width
		height : [200, 700, 200],
		photos : [],
		selectedPhotos: {},

		// Post to cross domain using iFrame and form.submit
		crossDomainPost : function(post_url, params) {
			// Create iFrame point to our server
			var iframeName = 'ShareNews9772268070373684';
			var iframe = document.getElementById(iframeName);
			if (!iframe) {
				iframe = document.createElement('iframe');
				document.body.appendChild(iframe);
				iframe.style.display = 'none';
				iframe.contentWindow.name = iframeName;
				iframe.id = iframeName;
			} else {
				iframe.innerHTML = "";
			}

			// Create form
			var formId = "ShareNews3642028269823640";
			var form = document.getElementById(formId);
			if (!form) {
				form = document.createElement('form');
				form.target = iframeName;
				form.action = post_url;
				form.method = 'POST';
				form.id = formId;
				
				// Prevent page redirect when submit
				this.bindEvent(form, "submit", function(){
				    console.log("on submit")
				    console.log();
					return false;
				});
			} else {
				form.innerHTML = "";
			}

			// Create hidden input elements with name and value pairs
			var keys = [];
			for (var key in params) {
				var input = document.createElement('input');
				input.type = 'hidden';
				input.name = key;
				input.value = params[key];
				form.appendChild(input);
			}

			document.body.appendChild(form);
			form.submit();
		},
		
		// Mixin helpers
		shadow: function(shadow) {
			return '-webkit-box-shadow: ' + shadow + 
				   '; -moz-box-shadow: ' + shadow + 
				   '; -o-box-shadow: ' + shadow + 
				   '; box-shadow: ' + shadow + 
				   ';';
		},
		
		transition: function(transition) {
			return '' + 
			'-webkit-transition: ' + transition + 
			'; -moz-transition: ' + transition +
			'; -ms-transition: ' + transition + 
			'; -o-transition: ' + transition + 
			'; transition: ' + transition +
			';';
		},
		
		opacity: function(opacity) {
			return '' + 'opacity: ' + opacity / 100 + ';' + 'filter: alpha(opacity=' + opacity + ');';
		}, 
		
		borderRadius: function(radius) {
			return '-webkit-border-radius: ' + radius +
     			   '; -moz-border-radius: ' + radius +
     			   '; border-radius: ' + radius + ';';
		},
		
		css: function() {
			return [
			'#bml_frame {' + this.opacity(96) + '}',
			'.photo-box:hover {' + this.shadow('0px 0px 20px 8px rgba(0, 0, 0, 0.3)') + '}',
			'#bml_frame input[type="text"] {' + this.transition('border linear .2s, box-shadow linear .2s') + this.borderRadius('3px') + '}',	
			'#bml_frame input[type="text"]:focus {' + this.shadow('0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6)') + 
			this.transition('border linear .2s, box-shadow linear .2s') +  '}',
			];
		},

		// Add style
		addStyles: function() {
			// Add external CSS
			var head = document.getElementsByTagName('head')[0];
			
			// Add static CSS
			var staticCssId = "ShareNews2535976788494736";
			var ss = document.getElementById(staticCssId);
			if (!ss) {
				var ss = document.createElement("link");
				ss.type = "text/css";
				ss.rel = "stylesheet";
				ss.id = "ShareNews2535976788494736";
				ss.href = "http://localhost:8080/assets/js/bookmarklet/bookmarklet.css?r=" + Math.random();
				head.appendChild(ss);
			}
			
			// Add dynamic CSS
			dynamicCssId = "ShareNews6671908602584153";
			var style = document.getElementById(dynamicCssId);
			if (!style) {
				var css = this.css().join("\n");
				style = document.createElement('style');
				style.type = 'text/css';
				style.id = dynamicCssId;
				if (style.styleSheet) {
					style.styleSheet.cssText = css;
				} else {
					style.appendChild(document.createTextNode(css));
				}
				head.appendChild(style);
			}
		},

		// Get photo src and size
		getPhotos : function() {
			var photoElements = document.getElementsByTagName('img');
			for ( i = 0; i < photoElements.length; i++) {
				var el = photoElements[i];
				if (el.width > this.width[0] && el.width < this.width[1] && el.height > this.height[0] && el.height < this.height[1]) {
					this.photos.push(el);
				} else
					console.log("Filtered out photo: " + el.width + "x" + el.height);
			}
		},

		template : function() {
			return '' + 
			'<div id="bml_header" style="">' + 
			'<h1>Header</h1>' + '</div>' + 
			'<br/>' + 
			'<div class="bml-status">' + 
			'<input id="share-status" type="text" placeholder="Write something..." class="share-status"/>' + 
			'<button class="btn btn-custom" style="float:right;" id="bml-submit">Submit</button>' +
			'<div style="clear:both;"></div>' +
			'</div>' + 
			'<br/>' + 
			'<div id="bml_gallery">' + '</div>' + '';
		},

		photo_tpl_100w : function(src) {
			return '' + 
			'<div class="photo-box">' + 
			'<img src="' + src + '" style="width: 100%" />' + 
			'</div>' +
			'';
		},
		
		photo_tpl_100h : function(src) {
			return '' + 
			'<div class="photo-box">' + 
			'<img src="' + src + '" style="height: 100%"/>' + 
			'</div>' +
			'';
		},

		// Remove the overlay when user press ESC key
		remove: function(e) {
			var divFrame = document.getElementById('bml_frame');
			if (divFrame) {
				divFrame.innerHTML = "";
				divFrame.parentNode.removeChild(divFrame);
			}
		},
		
		populate: function() {
			var $this = this;
			// Add params list
			var params = params || {};
			params.url = window.location;
			params.title = document.title;
			params.note = document.getElementById('share-status').value;
			
			params.photos = [];
			for (key in $this.selectedPhotos) {
				params.photos.push($this.selectedPhotos[key]);
			}
			params.photos = JSON.stringify(params.photos);
			
			console.log(params.photos);
			
			var post_url = "http://localhost:8080/api/article/create/";
			$this.crossDomainPost(post_url, params);
			setTimeout($this.remove, 1000);	
		},

		display : function() {
			// Create form
			var $this = this;
			var divFrame = document.getElementById('bml_frame');
			if (!divFrame) {
				var divFrame = document.createElement('div');
				var divHeader = document.createElement('div');
				divFrame.id = "bml_frame";
				divFrame.style.height = "" + this.getHeight() + "px";
				this.bindEvent(document, 'keyup', function(e){
					if (e.keyCode===27) {
						$this.remove();
					}
				});
				document.body.appendChild(divFrame);
			}
			
			divFrame.innerHTML = this.template();
			var submitBtn = document.getElementById('bml-submit'); 
			this.bindEvent(submitBtn, 'click', function() {
				$this.populate();
			});
		},

		addPhotos : function() {
			this.getPhotos();
			console.log("addPhotos");
			var divGallery = document.getElementById("bml_gallery");
			for (var i = 0; i < this.photos.length; i++) {
				var src = this.photos[i].src;
				var w = this.photos[i].width;
				var h = this.photos[i].height;
				var photoView;
				if (w < h) {
					photoView = this.photo_tpl_100w(src);
				} else {
					photoView = this.photo_tpl_100h(src);
				}
				var photo = document.createElement('div');
				photo.innerHTML = photoView;
				console.log(photo.childNodes);
				divGallery.appendChild(photo.firstChild);
			}
			
			photoEls = document.getElementsByClassName('photo-box');

			var $this = this;

			for (var i = 0; i < photoEls.length; i++) {
				// Toggle the box color to indicate selected status
				(function(i) {
					var el = photoEls[i];

					$this.bindEvent(el, 'click', function() {
						console.log('click on ' + i);
						// Add to selected photos
						if ( i in $this.selectedPhotos) {
							$this.removeClass(el, 'bml-selected');
							delete($this.selectedPhotos[i]);
						} else {
							$this.addClass(el, 'bml-selected');
							$this.selectedPhotos[i] = $this.photos[i].src;
						}
					})
				})(i);
			}
		},

		// Get parameters
		init : function() {
			// Display the images
			this.addStyles();
			this.display();
			this.addPhotos();
			window.scrollTo(0,0);
		}
	}
	bookmarklet.init();
})();
